package com.leonzhangxf.server;

import com.leonzhangxf.server.service.ServerStarter;
import org.springframework.beans.BeansException;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.Collections;
import java.util.Optional;

/**
 * @author leonzhangxf
 */
@SpringBootApplication
public class ServerApplication implements ApplicationRunner, ApplicationContextAware {

    private ApplicationContext applicationContext;

    public static void main(String[] args) {
        new SpringApplicationBuilder(ServerApplication.class).run(args);
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        String port = Optional.ofNullable(args)
            .map(arguments -> arguments.getOptionValues("port"))
            .orElse(Collections.singletonList("8999")).get(0);
        ServerStarter.startServer(Integer.parseInt(port), applicationContext);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
